#include"mystdio.h"

MyFile* my_fopen(const char* path,const char* fg)
{
    int flag = 0;//标记位
    int IsCreate = 0;//文件是否需要创建
    mode_t mode = 0666;
    if(strcmp(fg,"w") == 0)
    {
        flag = (O_WRONLY | O_CREAT | O_TRUNC);
        IsCreate = 1;
    }
    else if(strcmp(path,"r") == 0)
    {
        flag = O_RDONLY;
    }
    else if(strcmp(path,"a") == 0)
    {
        flag = (O_WRONLY | O_CREAT | O_APPEND);
        IsCreate = 1;
    }
    else {}
    int fd = 0;
    if(IsCreate)
    {
        fd = open(path,flag,mode);
    }
    else 
        fd = open(path,flag);
    if(fd < 0) return NULL;
    
    MyFile* FilePoint = (MyFile*)malloc(sizeof(MyFile));
    if(FilePoint == NULL) return NULL;
    FilePoint->fileno = fd;
    FilePoint->flags = FLUSH_LINE;
    FilePoint->pos = 0;
    return FilePoint;
}

void My_Flussh(MyFile* fp)
{
    write(fp->fileno,fp->Cache,fp->pos);
    fp->pos = 0;//清空缓冲区
}
void MyFwrite(MyFile* fp,const char* buf,int len)
{
    memcpy(fp->Cache+fp->pos,buf,len);
    fp->pos += len;

    if(fp->flags & FLUSH_LINE && fp->Cache[fp->pos-1] =='\n')
    {
        My_Flussh(fp);
    }
}
void My_fclose(MyFile* fp)
{
    My_Flussh(fp);
    close(fp->fileno);
    free(fp);
}
